package com.authine.cloudpivot.web.api.controller;


import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.web.api.controller.base.BaseQueryRuntimeController;
import com.authine.cloudpivot.web.api.handler.CustomizedOrigin;
import com.authine.cloudpivot.web.api.service.FescoadTwoDevelopmentService;
import com.authine.cloudpivot.web.api.vo.StoreSupervisor;
import com.authine.cloudpivot.web.api.vo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "文件上传", tags = "系统管理::文件上传")
@Controller
@RequestMapping("/api/runtime/query")
@Slf4j
@CustomizedOrigin(level = 0)
public class ExcelController extends BaseQueryRuntimeController {


    @Autowired
    private FescoadTwoDevelopmentService fescoadTwoDevelopmentService;


    @ApiOperation(value = "列表文件上传")
    @PostMapping("/upload_file")
    public String importFile(MultipartFile file) {
            return uploadFile(file);
        }

    public static String uploadFile(MultipartFile file) {
        String filePath = getFilePath();
        String fileName = System.currentTimeMillis() + file.getOriginalFilename();
        filePath = filePath + "/" + fileName;
        try {
            File fileTemplate = new File(filePath);
            file.transferTo(fileTemplate);
            return fileName;
        } catch (Exception e) {
            log.error("", e);
        }
        return "";
    }




    @ApiOperation(value = "列表文件上传")
    @GetMapping("/upload_file1")
    public String importFile1(String  file) {
        String s = file;
        log.info(file);
        String reutnrName = "";
        try {
            List<StoreSupervisor> storeSupervisor = excelToShopIdList(s);
            for (int i = 0; i <storeSupervisor.size() ; i++) {
                //查询项目存在吗
                String id =  fescoadTwoDevelopmentService.selectProject(storeSupervisor.get(i).getSubjectname(),storeSupervisor.get(i).getPeojectno());
                if(id==null){
                    storeSupervisor.remove(i);
                    reutnrName +=storeSupervisor.get(i).getSubjectname()+";";
                    i= i -1;
                }else{
                    storeSupervisor.get(i).setName("门店督导列表-项目立项-"+storeSupervisor.get(i).getStorename());
                    storeSupervisor.get(i).setSubjectname(id);
                    storeSupervisor.get(i).setId(fescoadTwoDevelopmentService.getId());
                    User user = fescoadTwoDevelopmentService.getOwner(storeSupervisor.get(i).getOwner());


                    storeSupervisor.get(i).setStorename(fescoadTwoDevelopmentService.getStoreName(storeSupervisor.get(i).getStorename(),storeSupervisor.get(i).getStorenum()));
                    storeSupervisor.get(i).setOwner(user.getId());
                    storeSupervisor.get(i).setCreater(user.getId());
                    storeSupervisor.get(i).setCreatedtime(new Date());
                    if(storeSupervisor.get(i).getMember()!=null){
                        //督导 存储id
                        User user1 = fescoadTwoDevelopmentService.getOwner(storeSupervisor.get(i).getMember());
                        Map map = new HashMap();
                        List<Map> list = new ArrayList<>();
                        map.put("id",user1.getId());
                        map.put("type","3");
                        list.add(map);
                        storeSupervisor.get(i).setMember(JSON.toJSONString(list));
                      // fescoadTwoDevelopmentService.sendMessageToDuDao(user1.getUserId(),storeSupervisor.get(i).getStorename());
                    }
                    //执行经理 存储id
                    if(storeSupervisor.get(i).getEmanager()!=null){
                        User user2 = fescoadTwoDevelopmentService.getOwner(storeSupervisor.get(i).getEmanager());
                        Map map = new HashMap();
                        List<Map> list = new ArrayList<>();
                        map.put("id",user2.getId());
                        map.put("type","3");
                        list.add(map);
                        storeSupervisor.get(i).setEmanager(JSON.toJSONString(list));
                    }
                }
            }
            fescoadTwoDevelopmentService.insertAll(storeSupervisor);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }





    public static File getFile(String fileName) {
        String filePath = getFilePath() + "/" + fileName;
        File fileTemplate = new File(filePath);
        return fileTemplate;
    }

    /**
     * 获取和创建临时文件保存目录,与项目所在目录同级
     */
    public static String getFilePath() {
        try {
            String onlinePath = System.getProperty("user.dir") + File.separator + "upload" + File.separator;
            log.info("onlinePath");
            log.info(onlinePath);
            File upload = new File(onlinePath, "template/");
            if (!upload.exists()) {
                upload.mkdirs();
            }
            log.info("upload.getAbsolutePath()----");
            log.info(upload.getAbsolutePath());
            return upload.getAbsolutePath();
        } catch (Exception e) {
            log.error("", e);
        }
        return "";
    }



    public  List<StoreSupervisor> excelToShopIdList(String fileName) throws Exception{
        //用字节流的方式先读取到你想要的excel的文件
        File file = getFile(fileName);
        Workbook wb = WorkbookFactory.create(new FileInputStream(file));
        Sheet sheet = wb.getSheetAt(0);
        //获取第一行  从0开始
        int firstrow=sheet.getFirstRowNum();
        //获取最后一行
        int lastrow=sheet.getLastRowNum();
        //循环行数依次获取列数
        List<StoreSupervisor> wList = new ArrayList<>();
        b:for (int i = 1; i < lastrow+1; i++) {
            Map map = new HashMap<>();
            //获取哪一行i
            StoreSupervisor storeSupervisor = new StoreSupervisor();
            Row row=sheet.getRow(i);
            if (row!=null) {
                //获取这一行的第一列 从0开始
                int firstcell=    row.getFirstCellNum();
                //获取这一行的最后一列
                int lastcell=    row.getLastCellNum();
                //创建一个集合，用处将每一行的每一列数据都存入集合中

                a:for (int j = firstcell; j <lastcell; j++) {
                    //获取第j列
                    Cell cell=row.getCell(j);
                    if(cell==null||cell.toString().trim().equals("")){

                        if(j==0){
                            storeSupervisor.setName("");//数据标题
                        }else if(j==1){
                            storeSupervisor.setOwner(null);//拥有者
                        }else if(j==2){
                            storeSupervisor.setSequenceno("");//单据号
                        }else if(j==3){
                            storeSupervisor.setSubjectname("");
                        }else if(j==4){
                            storeSupervisor.setPeojectno("");
                        }else if(j==5){
                            storeSupervisor.setStorename("");
                        }else if(j==6){
                            storeSupervisor.setStorenum("");
                        }else if(j==7){
                            storeSupervisor.setMember("");
                        }else if(j==8){
                            storeSupervisor.setStorestatus("");
                        }else if(j==9){
                            storeSupervisor.setStartdate(null);
                        }else if(j==10){
                            storeSupervisor.setEnddate(null);
                        }else if(j==11){
                            storeSupervisor.setCityname("");
                        }else if(j==12){
                            storeSupervisor.setProvince("");
                        }else if(j==13){
                            storeSupervisor.setEmanager(null);
                        }

                    }else{
                        if(j==0){
                            storeSupervisor.setName(cell.toString());//数据标题
                        }else if(j==1){
                            storeSupervisor.setOwner(cell.toString());//拥有者
                        }else if(j==2){
                            storeSupervisor.setSequenceno(cell.toString());//单据号
                        }else if(j==3){
                            storeSupervisor.setSubjectname(cell.toString());
                        }else if(j==4){
                            storeSupervisor.setPeojectno(cell.toString());
                        }else if(j==5){
                            storeSupervisor.setStorename(cell.toString());
                        }else if(j==6){
                            storeSupervisor.setStorenum(cell.toString());
                        }else if(j==7){
                            storeSupervisor.setMember(cell.toString());
                        }else if(j==8){
                            storeSupervisor.setStorestatus(cell.toString());
                        }else if(j==9){
                            Date dateCellValue = cell.getDateCellValue();
                            storeSupervisor.setStartdate(dateCellValue);
                        }else if(j==10){
                          //  SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                         //   Date date1 = new SimpleDateFormat("yyyy/MM/dd").parse(cell.toString());
                            Date dateCellValue = cell.getDateCellValue();
                            System.out.println(dateCellValue);
                          storeSupervisor.setEnddate(dateCellValue);
                        }else if(j==11){
                            storeSupervisor.setCityname(cell.toString());
                        }else if(j==12){
                            storeSupervisor.setProvince(cell.toString());
                        }else if(j==13){
                            storeSupervisor.setEmanager(cell.toString());
                        }
                    }
                }

                wList.add(storeSupervisor);
            }

        }
        return wList;
    }

    public static void main(String args[]) {

        try {
            String time="2010-10-01";
            SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
            Date date=formatter.parse(time);
            System.out.println(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
